
import { useTonConnectUI, useTonAddress } from '@tonconnect/ui-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'
import { GtagEvent } from '../../google/analytics/Event';
import gtag from '../../google/analytics';
import Icon from '../../component/Icon';
import Modal from '../../component/Modal';
import { formatStrToPoint } from '../../utils/string';
import { taskDone } from '../../service';

const Container = styled.div`
    font-size: .75rem;
    font-weight: 300;
    color: white;
    display: flex;
    justify-content: end;
    align-items: center;
    height: 100%;
    margin-right: 1.125rem;
    .title {
        overflow: hidden; 
        text-overflow: ellipsis;
        white-space:nowrap;
        display: block;
        max-width: 9.375rem;
    }
    .icon {
        margin-left: .4375rem;
    }
`
const ModalContent = styled.div`
    color: white;
`

const ModalTitle = styled.div`
    color: white;
    text-align: center;
    width: 100%;
`

const Connect: React.FC = () => {
    const { t } = useTranslation()
    const [tonConnectUI] = useTonConnectUI();
    const userFriendlyAddress = useTonAddress();

    const title = useMemo(() => {
        return formatStrToPoint(userFriendlyAddress, 8, 8) || t('ton.connect')
    }, [userFriendlyAddress, t])

    const onConnect = async () => {
        if (tonConnectUI.connected) {
            return
        }

        const unsubscribe = tonConnectUI.onModalStateChange((state) => {
            if (state.status === 'opened') {
                return
            }
            if (state.closeReason === 'wallet-selected' && tonConnectUI.connected) {
                taskDone({ taskId: '19' })
            }
            unsubscribe()
        })
        gtag.event(GtagEvent.Connect)
        await tonConnectUI.openModal()
    }

    const onDisConnect = async () => {
        if (!tonConnectUI.connected) {
            return
        }

        const modal = Modal.info({
            title: <ModalTitle>{t('common.warning')}</ModalTitle>,
            content: {
                content: <ModalContent>{t('ton.disconnectNoti')}</ModalContent>,
            },
            isLodingOk: true,
            okText: t('common.confirm'),
            onOk: async () => {
                await tonConnectUI.disconnect()
                modal.destroy()
            },
            cancelText: t('common.cancel'),
            onCancel: () => {
                modal.destroy()
            }
        })
    }

    return <>
        <Container onClick={onConnect}>
            <div className='title'>
                {title}
            </div>
            {tonConnectUI.connected && <Icon
                onClick={onDisConnect}
                className='icon'
                width='1.0625rem'
                name='icon_trash'
            />}
        </Container>
    </>
}

export default Connect